<?php
require_once('common.php');
$ticket = "";
$account = "";
$channel = "bbbug.com";
$state = sha1(time() . rand(100000, 999999));
if (!empty($_GET['logout'])) {
    header("Location: redirect.php");
    die;
}
if (empty($_COOKIE['userInfo'])) {
    header("Location: redirect.php");
    die;
}
if (empty($_COOKIE['version']) || $_COOKIE['version'] < strtotime('2020-06-12 22:40:00')) {
    header("Location: redirect.php");
    die;
}
$userInfo = json_decode($_COOKIE['userInfo'], true);
$account = $userInfo['id'];
$ticket = sha1("account" . $account . "channel" . $channel . WEBSOCKET_KEY);
// print_r($userInfo);die;

$isMaster = false;
if (in_array($userInfo['id'], ['2658116', '145025'])) {
    $isMaster = true;
}

?>
<!DOCTYPE html>
<html>

<head>
    <title>程序员聊天室</title>
    <meta name="referrer" content="never">
    <meta charset="UTF-8">
    <meta content='程序员,设计师,coder,产品设计,程序开发,软件开发,网站建设,小程序,聊天室,划水,水群,前端,后端,数据库,工程师' name='Keywords'>
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta content='一个程序员的佛系划水聊天室，欢迎你的加入' itemprop='description' name='Description'>
    <link rel="stylesheet" href="static/css/element.css">
    <link rel="stylesheet" href="static/css/style.css?version=<?echo time();?>">
</head>

<body>
    <div id="app" v-cloak>
        <div class="menu">
            <a href="javascript:void(0)" @click="clearAllBlackList" v-if="isMaster">大赦天下</a>
            <a href="javascript:void(0)" @click="clearHistory">清空记录</a>
            <a href="/?logout=1">重新登录</a>
            <a href="javascript:void(0)" @click="switchNotification">{{notificateStatus?"关闭通知":"打开通知"}}</a>
            <a href="https://gitee.com/hamm/ChatRoom" target="_blank">开源地址</a>
        </div>
        <div class="main">
            <div class="chat" id="chatRecord">
                <div v-for="(item,index) in messageList">
                    <div v-if="item.msgType=='img'">
                        <div class="item" v-if="item.user.id != userInfo.id">
                            <img class="head" :src="item.user.avatar_url" width="40px" height="40px" @click="showBigImage($event)" />
                            <div class="detail">
                                <div>
                                    <a class="at_link" @click="atUser(item.user.id,item.user.name)">@</a>
                                    <a v-if="item.user.plat=='码云'" class="title" :title="['点击查看'+item.user.name+'的码云主页']" :href="['https://gitee.com/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">码云</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='开源中国'" class="title" :title="['点击查看'+item.user.name+'的开源中国主页']" :href="['https://my.oschina.net/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">开源中国</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='QQ'" class="title" title="暂不支持打开QQ" href="javascript:;">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">QQ</el-tag>
                                    </a>
                                    <a v-if="!item.user.plat" class="title" title="未知的登录平台" href="javascript:;">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">未知平台</el-tag>
                                    </a>
                                </div>
                                <div class="img">
                                    <img :src="['./upload/'+item.content]" @click="showBigImage($event)" onerror="this.src='404.jpg'" />
                                </div>
                            </div>
                            <div class="time">{{item.time}}
                                <span v-if="isMaster">
                                    <a class="controll_item" @click="login_set(item.user.id,item.user.name)">踢出</a>
                                    <a class="controll_item" @click="login_delete(item.user.id,item.user.name)">允许</a>
                                    <a class="controll_item" @click="chat_set(item.user.id,item.user.name)">禁言</a>
                                    <a class="controll_item" @click="chat_delete(item.user.id,item.user.name)">解禁</a>
                                </span>
                            </div>
                        </div>
                        <div class="item mine" v-if="item.user.id == userInfo.id">
                            <img class="head" :src="item.user.avatar_url" width="40px" height="40px" @click="showBigImage($event)" />
                            <div class="detail">
                                <div>
                                    <a v-if="item.user.plat=='码云'" class="title" :title="['点击查看'+item.user.name+'的码云主页']" :href="['https://gitee.com/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">码云</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='开源中国'" class="title" :title="['点击查看'+item.user.name+'的开源中国主页']" :href="['https://my.oschina.net/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">开源中国</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='QQ'" class="title" title="暂不支持打开QQ" href="javascript:;">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">QQ</el-tag>
                                    </a>
                                    <a v-if="!item.user.plat" class="title" title="未知的登录平台" href="javascript:;">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">未知平台</el-tag>
                                    </a>
                                </div>
                                <div class="img">
                                    <img :src="['./upload/'+item.content]" @click="showBigImage($event)" onerror="this.src='404.jpg'" />
                                </div>
                            </div>
                            <div class="time">{{item.time}}</div>
                        </div>
                    </div>
                    <div v-if="item.msgType=='text'">
                        <div class="item" v-if="item.user.id != userInfo.id">
                            <img class="head" :src="item.user.avatar_url" width="40px" height="40px" @click="showBigImage($event)" />
                            <div class="detail">
                                <div>
                                    <a class="at_link" @click="atUser(item.user.id,item.user.name)">@</a>
                                    <a v-if="item.user.plat=='码云'" class="title" :title="['点击查看'+item.user.name+'的码云主页']" :href="['https://gitee.com/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">码云</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='开源中国'" class="title" :title="['点击查看'+item.user.name+'的开源中国主页']" :href="['https://my.oschina.net/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">开源中国</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='Github'" class="title" :title="['点击查看'+item.user.name+'的Github主页']" :href="['https://github.com/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">Github</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='QQ'" class="title" title="暂不支持打开QQ" href="javascript:;">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">QQ</el-tag>
                                    </a>
                                    <a v-if="!item.user.plat" class="title" title="未知的登录平台" href="javascript:;">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">未知平台</el-tag>
                                    </a>
                                </div>
                                <div class="content">{{item.content}}</div>
                            </div>
                            <div class="time">{{item.time}}
                                <span v-if="isMaster">
                                    <a class="controll_item" @click="login_set(item.user.id,item.user.name)">踢出</a>
                                    <a class="controll_item" @click="login_delete(item.user.id,item.user.name)">允许</a>
                                    <a class="controll_item" @click="chat_set(item.user.id,item.user.name)">禁言</a>
                                    <a class="controll_item" @click="chat_delete(item.user.id,item.user.name)">解禁</a>
                                </span>
                            </div>
                        </div>
                        <div class="item mine" v-if="item.user.id == userInfo.id">
                            <img class="head" :src="item.user.avatar_url" width="40px" height="40px" @click="showBigImage($event)" />
                            <div class="detail">
                                <div>
                                    <a v-if="item.user.plat=='码云'" class="title" :title="['点击查看'+item.user.name+'的码云主页']" :href="['https://gitee.com/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">码云</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='开源中国'" class="title" :title="['点击查看'+item.user.name+'的开源中国主页']" :href="['https://my.oschina.net/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">开源中国</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='Github'" class="title" :title="['点击查看'+item.user.name+'的Github主页']" :href="['https://github.com/'+item.user.login]" target="_blank">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">Github</el-tag>
                                    </a>
                                    <a v-if="item.user.plat=='QQ'" class="title" title="暂不支持打开QQ" href="javascript:;">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">QQ</el-tag>
                                    </a>
                                    <a v-if="!item.user.plat" class="title" title="未知的登录平台" href="javascript:;">
                                        {{item.user.name}}
                                        <el-tag size="small" type="info" class="from">未知平台</el-tag>
                                    </a>
                                </div>
                                <div class="content">{{item.content}}</div>
                            </div>
                            <div class="time">{{item.time}}</div>
                        </div>
                    </div>
                    <div class="system" v-if="item.msgType=='system'">
                        <span>系統消息：{{item.content}}</span>
                    </div>
                </div>
            </div>
            <div class="lockscreen" @click="switchLockScreen">
                <i class="el-icon-lock" v-if="lockScreen"></i>
                <i class="el-icon-unlock" v-if="!lockScreen"></i>
            </div>
            <div class="atbox">
                <el-tag closable type="warning" v-if="at" @close="at=''">
                    {{at_show}}
                </el-tag>
            </div>
            <div class="form">
                <textarea id="inputId" placeholder="Press Enter to send..." v-model="message" @keydown.13="sendMessage" @keydown.8="delInput"></textarea>
                <div class="toolbar">
                    <el-button-group>
                        <el-upload action="upload.php" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <el-button size="mini" icon="el-icon-film" title="发送图片"></el-button>
                        </el-upload>
                    </el-button-group>
                </div>
            </div>
        </div>
        <el-dialog title="查看大图" :visible.sync="dialogBigHeadimgVisible" width="50%" center>
            <span><img :src="nowHeadImg" width="100%" height="100%" /></span>
        </el-dialog>
    </div>
</body>
<script src="static/js/vue-2.6.10.min.js"></script>
<script src="static/js/axios.min.js"></script>
<script src="static/js/element.js"></script>
<script src="static/js/vue-clipboard.min.js"></script>
<script>
    var userInfo = '<?php echo json_encode($userInfo); ?>';
    var account = '<?php echo $account; ?>';
    var ticket = '<?php echo $ticket; ?>';
    var channel = '<?php echo $channel; ?>';
    var isMaster = '<?php echo $isMaster; ?>';
    new Vue({
        el: '#app',
        data() {
            return {
                at: 0,
                at_show: "",
                message: "",
                messageList: [],
                wss: null,
                wssTimer: null,
                msgTimer: null,
                heartBeatTimer: null,
                dialogBigHeadimgVisible: false,
                nowHeadImg: "",
                notificateStatus: true,
                lockScreen: false,
                userInfo: JSON.parse(userInfo),
                isMaster: isMaster
            }
        },
        created() {
            var that = this;
            that.wssInit();
            var msgList = localStorage.getItem('msgList');
            if (msgList) {
                try {
                    that.messageList = JSON.parse(msgList);
                } catch (e) {}
            }
            that.messageList.push({
                content: '聊天室即将改版，增添更多属于程序员的玩法，如果你有好的建议或意见，欢迎加入QQ群(1019758581)告诉我们',
                msgType: 'system'
            });
        },
        mounted() {
            document.getElementById('inputId').focus();
        },
        updated() {
            var that = this;
            if (!that.lockScreen) {
                let ele = document.getElementById('chatRecord');
                ele.scrollTop = ele.scrollHeight;
            }
        },
        methods: {
            clearHistory() {
                var that = this;
                that.$confirm('是否确认清空本地聊天记录?', '删除聊天记录', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function() {
                    that.messageList = [];
                    localStorage.setItem('msgList', JSON.stringify(that.messageList));
                    that.messageList.push({
                        content: '历史聊天记录清理成功',
                        msgType: 'system'
                    });
                }).catch(function() {});
            },
            handleAvatarSuccess(res, file) {
                var that = this;
                if (res.code == 200) {
                    var msgData = {
                        content: res.data.path,
                        msgType: 'img',
                        user: that.userInfo,
                        time: that.getNowTime()
                    };
                    that.wss.send(JSON.stringify({
                        account: account,
                        channel: channel,
                        ticket: ticket,
                        type: 'channel',
                        to: channel,
                        msg: encodeURIComponent(JSON.stringify(msgData))
                    }));
                    clearTimeout(that.msgTimer);
                    that.msgTimer = setTimeout(function() {
                        that.msgTimer = null;
                    }, 1000);
                } else {
                    this.$message.error(res.msg);
                }
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('发送图片只能是 JPG/PNG/GIF 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('发送图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            atUser(user_id, user_name) {
                this.at = user_id;
                this.at_show = '@' + user_name;
            },
            login_set(user_id, user_name) {
                this.userControl('login_set', user_id, user_name);
            },
            login_delete(user_id, user_name) {
                this.userControl('login_delete', user_id, user_name);
            },
            chat_set(user_id, user_name) {
                this.userControl('chat_set', user_id, user_name);
            },
            chat_delete(user_id, user_name) {
                this.userControl('chat_delete', user_id, user_name);
            },
            clearAllBlackList() {
                var that = this;
                var msgData = {
                    content: '管理员大赦天下，所有人可登录可发言啦',
                    msgType: 'delete_all',
                    user: that.userInfo,
                    time: that.getNowTime()
                };
                that.wss.send(JSON.stringify({
                    account: account,
                    channel: channel,
                    ticket: ticket,
                    type: 'channel',
                    to: channel,
                    msg: encodeURIComponent(JSON.stringify(msgData))
                }));
            },
            userControl(type, user_id, user_name) {
                var that = this;
                var msgData = {
                    content: '',
                    msgType: type,
                    account: user_id,
                    name: user_name,
                    user: that.userInfo,
                    time: that.getNowTime()
                };
                that.wss.send(JSON.stringify({
                    account: account,
                    channel: channel,
                    ticket: ticket,
                    type: 'channel',
                    to: channel,
                    msg: encodeURIComponent(JSON.stringify(msgData))
                }));
            },
            switchLockScreen() {
                this.lockScreen = !this.lockScreen;
                if (this.lockScreen) {
                    this.messageList.push({
                        content: '已锁定屏幕,新消息将不会自动滚动',
                        msgType: 'system'
                    });
                } else {
                    this.messageList.push({
                        content: '新消息自动滚动已开启',
                        msgType: 'system'
                    });
                }
            },
            switchNotification() {
                this.notificateStatus = !this.notificateStatus;
                if (this.notificateStatus) {
                    this.messageList.push({
                        content: 'Chrome通知已开启,你将收到@新消息通知',
                        msgType: 'system'
                    });
                    if (window.Notification && Notification.permission !== "denied") {
                        Notification.requestPermission(function(status) { // 请求权限
                            if (status === 'granted') {
                                // 弹出一个通知
                                var n = new Notification("Chrome通知已开启", {
                                    body: "有@新消息的话我会在这里提示你哟~\n\n",
                                    icon: ""
                                });
                                // 两秒后关闭通知
                                setTimeout(function() {
                                    n.close();
                                }, 5000);
                            }
                        });
                    }
                } else {
                    this.messageList.push({
                        content: 'Chrome通知已关闭,你将无法收到@新消息通知',
                        msgType: 'system'
                    });
                }
            },
            showBigImage(e) {
                this.nowHeadImg = e.srcElement.src;
                this.dialogBigHeadimgVisible = true;
            },
            delInput: function(e) {
                var that = this;
                if (!that.message) {
                    that.at = "";
                }
            },
            sendMessage: function(e) {
                e.preventDefault();
                var that = this;
                if (!that.message) {
                    return;
                }
                if (that.msgTimer && that.userInfo.login != 'hamm') {
                    that.messageList.push({
                        content: '发送消息过于频繁，请稍候再试',
                        msgType: 'system'
                    });
                    return;
                }
                // that.message = that.message.replace("旺仔","旺仔爸爸");
                // that.message = that.message.replace("十三","十三爸爸");
                // that.message = that.message.replace("三木","三木爸爸");
                if (that.at) {
                    that.message = that.at_show + " " + that.message;
                }
                var msgData = {
                    content: that.message,
                    msgType: 'text',
                    at: that.at,
                    user: that.userInfo,
                    time: that.getNowTime()
                };
                that.wss.send(JSON.stringify({
                    account: account,
                    channel: channel,
                    ticket: ticket,
                    type: 'channel',
                    to: channel,
                    msg: encodeURIComponent(JSON.stringify(msgData))
                }));
                that.message = '';
                // that.at = 0;
                clearTimeout(that.msgTimer);
                that.msgTimer = setTimeout(function() {
                    that.msgTimer = null;
                }, 1000);
            },
            getNowTime() {
                var now = new Date();
                var hours = now.getHours();
                var minutes = now.getMinutes();
                var seconds = now.getSeconds();
                if (hours < 10) {
                    hours = "0" + hours;
                }
                if (minutes < 10) {
                    minutes = "0" + minutes;
                }
                if (seconds < 10) {
                    seconds = "0" + seconds;
                }
                return hours + ":" + minutes + ":" + seconds;
            },
            wssInit() {
                var that = this;
                that.wss = new WebSocket("wss://wss.hamm.cn/?account=" + account + "&channel=" + channel + "&ticket=" + ticket);
                that.wss.onopen = function(evt) {
                    // 监听Socket的关闭
                    var msgData = {
                        content: that.userInfo.name + "@" + that.userInfo.plat + " 已加入群聊",
                        msgType: 'system',
                        user: that.userInfo
                    };
                    that.heartBeat();
                    that.wss.send(JSON.stringify({
                        account: account,
                        channel: channel,
                        ticket: ticket,
                        type: 'channel',
                        to: channel,
                        msg: encodeURIComponent(JSON.stringify(msgData))
                    }));
                    that.wss.onclose = function(event) {
                        that.wssError();
                    };
                };
                that.wss.onmessage = function(event) {
                    try {
                        var obj = JSON.parse(decodeURIComponent(event.data));
                        if (that.messageList.length > 100) {
                            that.messageList.shift();
                        }
                        that.messageList.push(obj);
                        localStorage.setItem('msgList', JSON.stringify(that.messageList));
                        if (obj.msgType == 'text') {
                            if (obj.at == that.userInfo.id) {
                                that.$notify({
                                    title: obj.user.name + " @了你",
                                    message: obj.content,
                                    duration: 0
                                });
                            }
                            if (obj.user && obj.user.id != that.userInfo.id && obj.at == that.userInfo.id) {
                                if (window.Notification && Notification.permission !== "denied") {
                                    Notification.requestPermission(function(status) { // 请求权限
                                        if (status === 'granted') {
                                            // 弹出一个通知
                                            var n = new Notification(obj.user.name + " 说:", {
                                                body: obj.content + "\n\n",
                                                icon: obj.user.avatar_url
                                            });
                                            // 两秒后关闭通知
                                            setTimeout(function() {
                                                n.close();
                                            }, 5000);
                                        }
                                    });
                                }
                            }
                        }
                    } catch (e) {
                        console.log(e);
                    }
                };
                // 监听Socket的关闭
                that.wss.onerror = function(event) {
                    that.wssError();
                };
            },
            heartBeat() {
                var that = this;
                clearTimeout(that.heartBeatTimer);
                that.heartBeatTimer = setTimeout(function() {
                    that.wss.send('heartBeat');
                    that.heartBeat();
                }, 5000);
            },
            wssError() {
                var that = this;
                that.messageList.push({
                    content: '连接已断开，5s后将自动重连',
                    msgType: 'system'
                });
                clearTimeout(that.wssTimer);
                that.wssTimer = setTimeout(function() {
                    that.wssInit();
                }, 5000);
            }
        }
    });
</script>

</html>